package com.ysq.www.api.work.service.impl;

import com.alibaba.druid.util.StringUtils;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.UpdateWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.ysq.www.api.user.entity.User;
import com.ysq.www.api.user.mapper.UserMapper;
import com.ysq.www.api.work.entity.Approve;
import com.ysq.www.api.work.entity.CopyTo;
import com.ysq.www.api.work.entity.Synergy;
import com.ysq.www.api.work.mapper.ApproveMapper;
import com.ysq.www.api.work.mapper.CopyToMapper;
import com.ysq.www.api.work.mapper.SynergyMapper;
import com.ysq.www.api.work.service.ISynergyService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.ysq.www.common.result.ResultMsg;
import com.ysq.www.common.utils.Comm;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.ArrayList;
import java.util.List;

/**
 * <p>
 * 协同办公表 服务实现类
 * </p>
 *
 * @author dql
 * @since 2020-08-11
 */
@Service
public class SynergyServiceImpl extends ServiceImpl<SynergyMapper, Synergy> implements ISynergyService {


    @Autowired
    private ApproveMapper approveMapper;

    @Autowired
    private CopyToMapper copyToMapper;

    @Autowired
    private SynergyMapper synergyMapper;

    @Autowired
    private UserMapper userMapper;

    /**
     * 提交协同办公
     * @param synergy 协同办公对象
     * @return
     */
    @Override
    @Transactional
    public ResultMsg addSynergy(Synergy synergy) {
        //发起协同办公
        synergy.setCreateTime(Comm.getNow());
        boolean save = this.save(synergy);
        if (save){//创建审批表记录
            Approve ap = new Approve();
            ap.setType(2);
            ap.setContentId(synergy.getId());
            ap.setCheckId(synergy.getApproverId());
            ap.setSupperId(0);
            ap.setLowerId(0);
            ap.setCheckStatus(0);
            ap.setCreateTime(Comm.getNow());
            ap.setStatus(0);
            approveMapper.insert(ap);

            //创建抄送记录
            String copyIds = synergy.getCopyId();
            if (!StringUtils.isEmpty(copyIds)){
                List<CopyTo> cList = new ArrayList<>();
                String[] copyId = copyIds.split(";");
                for (String c : copyId) {
                    CopyTo ct = new CopyTo();
                    ct.setType(1);//协同办公类
                    ct.setContentId(synergy.getId());//内容id
                    ct.setUserId(Integer.parseInt(c));//抄送至用户的id
                    ct.setCreateTime(Comm.getNow());//创建时间
                    ct.setStatus(0);
                    cList.add(ct);
                }
                if (cList.size() > 0){
                    copyToMapper.insertList(cList);
                    //copyToMapper.insertListByNote(cList);
                }
            }
            return ResultMsg.INSERT_SUCCESS.setNewMsg("提交协同办公成功");
        }else return ResultMsg.INSERT_ERROR.setNewMsg("提交失败，内部错误");
    }

    /**
     * 查询我的已发起的协同待办
     * @param userId 用户id
     * @param pageNumber 页码
     * @param pageSize 页大小
     * @param time 日期
     * @return
     */
    @Override
    public IPage<Synergy> selectSponsorById(Integer userId, Integer pageNumber, Integer pageSize, String time) {
        QueryWrapper<Synergy> wrapper = new QueryWrapper<>();
        wrapper.eq("status",0).eq("user_id",userId);
        if (!StringUtils.isEmpty(time)){
            String startTime = time + " 00:00:00";
            String endTime = time + " 23:59:59";
            wrapper.between("create_time",startTime,endTime);
        }
        wrapper.orderByDesc("create_time");
        Page<Synergy> page = new Page<>(pageNumber,pageSize);
        IPage<Synergy> synergyIPage = synergyMapper.selectPage(page, wrapper);
        return synergyIPage;
    }

    /**
     * 查询待处理协同待办
     * @param userId 用户id（审批者id）
     * @param pageNumber 页码
     * @param pageSize 页大小
     * @param time 日期
     * @return
     */
    @Override
    public IPage<Synergy> selectByCheckId(Integer userId, Integer pageNumber, Integer pageSize, String time) {
        QueryWrapper<Synergy> wrapper = new QueryWrapper<>();
        wrapper.eq("approver_id",userId).eq("check_status",0).eq("status",0);
        if (!StringUtils.isEmpty(time)){
            String startTime = time + " 00:00:00";
            String endTime = time + " 23:59:59";
            wrapper.between("create_time",startTime,endTime);
        }
        wrapper.orderByDesc("create_time");
        Page<Synergy> page = new Page<>(pageNumber,pageSize);
        IPage<Synergy> sPage = synergyMapper.selectPage(page, wrapper);
        return sPage;
    }

    /**
     * 查询已处理协同待办
     * @param userId 审批人id
     * @param pageNumber 页码
     * @param pageSize 页大小
     * @param time 日期
     * @return
     */
    @Override
    public IPage<Synergy> selectDisposeById(Integer userId, Integer pageNumber, Integer pageSize, String time) {
        QueryWrapper<Synergy> wrapper = new QueryWrapper<>();
        wrapper.eq("status",0).eq("approver_id",userId).ne("check_status",0).
                ne("check_status",3);
        if (!StringUtils.isEmpty(time)){
            String startTime = time + " 00:00:00";
            String endTime = time + " 23:59:59";
            wrapper.between("create_time",startTime,endTime);
        }
        wrapper.orderByDesc("create_time");
        Page<Synergy> page = new Page<>(pageNumber,pageSize);
        IPage<Synergy> sPage = synergyMapper.selectPage(page, wrapper);
        return sPage;
    }

    /**
     * 查询抄送我协同待办
     * @param userId 用户id
     * @param pageNumber 页码
     * @param pageSize 页大小
     * @param time 日期
     * @return
     */
    @Override
    public IPage<Synergy> selectCopyToMe(Integer userId, Integer pageNumber, Integer pageSize, String time) {
        QueryWrapper<CopyTo> wrapper = new QueryWrapper<>();
        wrapper.eq("status",0).eq("type",1).eq("user_id",userId);
        List<CopyTo> cList = copyToMapper.selectList(wrapper);
        if (cList.isEmpty()) return null;
        List<Integer> idList = new ArrayList<>();
        for (CopyTo c : cList) {
            idList.add(c.getContentId());
        }
        QueryWrapper<Synergy> sWrapper = new QueryWrapper<>();
        sWrapper.eq("status",0).ne("check_status",3).in("id",idList);
        if (!StringUtils.isEmpty(time)){
            String startTime = time + " 00:00:00";
            String endTime = time + " 23:59:59";
            sWrapper.between("create_time",startTime,endTime);
        }
        sWrapper.orderByDesc("create_time");
        Page<Synergy> page = new Page<>(pageNumber,pageSize);
        IPage<Synergy> sPage = synergyMapper.selectPage(page, sWrapper);
        return sPage;
    }

    /**
     * 根据id查询详情
     * @param syId 协同办公id
     * @return
     */
    @Override
    public Synergy selectDetailById(Integer syId) {
        Synergy synergy = synergyMapper.selectDetailById(syId);
        Synergy receiveAndCopy = getReceiveAndCopy(synergy);
        return receiveAndCopy;
    }

    /**
     * 根据id查询待处理详情
     * @param syId 协同办公id
     * @return
     */
    @Override
    public Synergy selectPendingById(Integer syId) {
        Synergy synergy = synergyMapper.selectDetailById(syId);
        Synergy receiveAndCopy = getReceiveAndCopy(synergy);
        return receiveAndCopy;
    }

    /**
     * 根据id撤销协同办工
     * @param syId 协同办公id
     * @return ResultMsg
     */
    @Override
    public ResultMsg repealSynergyById(Integer syId) {
        Synergy sy = synergyMapper.selectById(syId);
        if (sy.getCheckStatus() != 0) return ResultMsg.UPDATE_ERROR.setNewMsg("撤销失败，该协同办公已处理不能撤销");
        sy.setCheckStatus(3);
        sy.setUpdateTime(Comm.getNow());
        this.updateById(sy);
        UpdateWrapper<Approve> wrapper = new UpdateWrapper<>();//修改审批记录
        wrapper.set("check_time",Comm.getNow()).set("check_status",3).set("update_time",Comm.getNow()).
                eq("type",2).eq("content_id",syId);
        approveMapper.update(null,wrapper);
        //synergyMapper.repealSynergyById(syId);
        return ResultMsg.UPDATE_SUCCESS.setNewMsg("撤销成功");
    }

    /**
     * 处理协同办公
     * @param syId 协同办公id
     * @param result 处理结果：1通过，2驳回
     * @return ResultMsg
     */
    @Override
    @Transactional
    public ResultMsg disposeSynergyById(Integer syId, Integer result) {
        Synergy sy = synergyMapper.selectById(syId);
        if (sy.getCheckStatus() != 0) return ResultMsg.UPDATE_ERROR.setNewMsg("处理失败，协同办公已处理或已撤销");
        sy.setCheckStatus(result);
        sy.setUpdateTime(Comm.getNow());
        this.updateById(sy);
        UpdateWrapper<Approve> wrapper = new UpdateWrapper<>();
        wrapper.set("check_time",Comm.getNow()).set("check_status",result).set("update_time",Comm.getNow()).
                eq("type",2).eq("content_id",syId);
        approveMapper.update(null,wrapper);
        return ResultMsg.UPDATE_SUCCESS.setNewMsg("处理成功");
    }

    /**
     * 公用方法
     */
    public Synergy getReceiveAndCopy(Synergy synergy){
        //获取接收人id字符串
        String[] uArray = synergy.getReceiveIds().split(";");
        List<Integer> idList = new ArrayList<>();
        for (String s : uArray) {
            idList.add(Integer.parseInt(s));
        }
        QueryWrapper<User> wrapper = new QueryWrapper<>();
        wrapper.eq("status",0).in("id",idList);
        List<User> userList = userMapper.selectList(wrapper);
        synergy.setReList(userList);
        String copyIds = synergy.getCopyId();//抄送人id字符串
        if (StringUtils.isEmpty(copyIds)) return synergy;
        String[] cArray = copyIds.split(";");
        List<Integer> cIdList = new ArrayList<>();
        for (String c : cArray) {
            cIdList.add(Integer.parseInt(c));
        }
        QueryWrapper<User> wrapper1 = new QueryWrapper<>();
        wrapper1.eq("status",0).in("id",cIdList);
        List<User> copyList = userMapper.selectList(wrapper1);
        synergy.setCopyList(copyList);
        return synergy;
    }

}
